package com.yakami.ocean.view.activity;

import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.yakami.ocean.AppManager;
import com.yakami.ocean.DeviceManager;
import com.yakami.ocean.R;
import com.yakami.ocean.ServerAPI;
import com.yakami.ocean.bean.News;
import com.yakami.ocean.event.Event;
import com.yakami.ocean.event.RxBus;
import com.yakami.ocean.utils.IntentHelper;
import com.yakami.ocean.view.activity.base.BaseHoldBackTabsActivity;
import com.yakami.ocean.view.fragment.AutoNewsListFragment;
import com.yakami.ocean.view.fragment.LoadFragment;

import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Yakami, Created on 2016/4/23
 */
public class SearchActivity extends BaseHoldBackTabsActivity {

    @Bind(R.id.edit_search) EditText mEditSearch;
    @Bind(R.id.btn_search) TextView mBtnSearch;
    @Bind(R.id.content) RelativeLayout mContentLayout;

    private LoadFragment mLoadFragment;
    private AutoNewsListFragment mFragment;

    @Override
    public void onCreate(Bundle savedInstanceBundle) {
        super.onCreate(savedInstanceBundle);

        setSearchBar();
        initTabs(savedInstanceBundle != null); //清理fragment
    }

    private void setSearchBar() {
        mEditSearch.setOnFocusChangeListener((view, hasFocus) -> {
                    if (hasFocus) {
                        DeviceManager.getSoftInputManager(AppManager.context).toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
                        mBtnSearch.setVisibility(View.VISIBLE);
                    }
                }
        );
        //搜索按钮自动显示和消失处理
        RxView.clicks(mEditSearch)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> {
                    mBtnSearch.setVisibility(View.VISIBLE);
                });
        mEditSearch.setOnEditorActionListener((textView, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search(textView.getText().toString());
                mBtnSearch.setVisibility(View.GONE);
                DeviceManager.hideSoftInput(mAppContext, getCurrentFocus());
                return true;
            }
            return false;
        });
        RxView.clicks(mBtnSearch)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe((Void) -> {
                    search(mEditSearch.getText().toString());
                    DeviceManager.hideSoftInput(mAppContext, getCurrentFocus());
                });
    }

    private void search(String str) {
        mLoadFragment = new LoadFragment();
        mFragment = new AutoNewsListFragment();
        mFragment.setRefreshListener(() -> {
            ServerAPI.getOceanAPI()
                    .search(str)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe((container) -> {
                        mFragment.setData(container.list);
                        mFragment.onSuccess();
                        RxBus.getInstance().send(Event.EventType.LOADED_SUCCESSFUL, null);
                    }, throwable -> {
                        throwable.printStackTrace();
                        mFragment.onError();
                        RxBus.getInstance().send(Event.EventType.LOAD_ERROR, null);
                    });
        });
        mFragment.setOnItemClickListener((pos, data) -> {
            startActivity(IntentHelper.newInstance(mContext, DetailActivity.class)
                    .putSerializable("data", (News) data)
                    .toIntent());
        });
        mLoadFragment.setFragment(mFragment);
        getSlideAnimTransaction().replace(R.id.content, mLoadFragment, "LOAD_FRAGMENT").commit();
    }


    @Override
    public int onBindLayout() {
        return R.layout.activity_search;
    }
}
